package wbbs.service;

import com.google.inject.Inject;
import com.google.inject.Singleton;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import wbbs.domain.User;

import java.sql.SQLException;

@Singleton
public class UserService {

    @Inject
    QueryRunner qr;

    public User findUser(String id) throws SQLException {
        return qr.query("select * from User where id=?", new BeanHandler<User>(User.class), id);
    }

    public void insertUser(User user) throws SQLException {
        qr.update("insert into User(id, pwd, name, head) values(?, ?, ?, ?)",
                user.id, user.pwd, user.name, user.head);
    }

    public int countUser() throws SQLException {
        return qr.query("select count(*) from User", new ScalarHandler<Number>()).intValue();
    }

    public PaginatedList<User> listUser(int page, int pageSize) throws SQLException {
        PaginatedList<User> list = new PaginatedList<User>(pageSize);
        list.setItemCount(countUser());
        list.setPage(page);
        list.addAll(qr.query("select * from User order by id limit ? offset ?",
                new BeanListHandler<User>(User.class), list.getPageSize(), list.getOffset()));
        return list;
    }

    public void updateUser(User user) throws SQLException {
        qr.update("update User set pwd=?, name=?, head=?",
                user.pwd, user.name, user.head);
    }
}
